package com.ccys.cms.service.consultation.impl;

import cn.hutool.core.util.ObjectUtil;
import com.ccys.cms.service.consultation.ConsultationOrderAndListService;
import com.ccys.common.util.HtmlUtils;
import com.ccys.common.util.Kit;
import com.ccys.common.vo.ResponseResult;
import com.ccys.db.cache.TranslationUtil;
import com.ccys.db.cache.UserUtil;
import com.ccys.db.dto.consultation.*;
import com.ccys.db.entity.TblBooking;
import com.ccys.db.entity.TblBookingGrab;
import com.ccys.db.entity.TblBookingUparcel;
import com.ccys.db.mapper.TblBookingGrabLogMapper;
import com.ccys.db.mapper.TblBookingGrabMapper;
import com.ccys.db.mapper.TblBookingMapper;
import com.ccys.db.mapper.TblBookingUparcelMapper;
import com.ccys.db.page.PageDto;
import com.ccys.db.rely.service.impl.BaseServiceImpl;
import com.ccys.db.vo.consultation.*;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @program: WhiteCoat
 * @description: 问诊订单和列表接口实现类
 * @author: ZhangJingCan
 * @create: 2023-12-27 15:17
 **/

@Service
@Slf4j
public class ConsultationOrderAndListServiceImpl extends BaseServiceImpl<TblBooking> implements ConsultationOrderAndListService {

    @Resource
    private TblBookingMapper tblBookingMapper;

    @Resource
    private TblBookingGrabMapper tblBookingGrabMapper;

    @Resource
    private TblBookingGrabLogMapper tblBookingGrabLogMapper;

    @Resource
    private TblBookingUparcelMapper tblBookingUparcelMapper;

    @Override
    public ResponseResult<PageInfo<ConsultationPageQueryVo>, BigDecimal> findConsultationBasePage(ConsultationPageQueryDto dto) {
        //开启分页
        PageDto.startPage();
        List<ConsultationPageQueryVo> list = tblBookingMapper.findConsultationBasePage(dto);
        PageInfo<ConsultationPageQueryVo> info = new PageInfo<>(list);
        //用于总额
        BigDecimal totalEarning = BigDecimal.ZERO.setScale(2, BigDecimal.ROUND_DOWN);
        //检查是否查询总金额数
        if (ObjectUtil.isNotEmpty(dto.getFindTotal())) {
            //判断为医生还是患者 - 0患者，1-医生
            if (0 == dto.getFindTotal() && ObjectUtil.isNotEmpty(dto.getMemId())) {
                //查询患者总额
                totalEarning = tblBookingMapper.findTotalPaymentByMemId(dto.getMemId());
            } else if (1 == dto.getFindTotal() && ObjectUtil.isNotEmpty(dto.getDoctorId())) {
                //查询医生总额
                totalEarning = tblBookingMapper.findTotalEarningByDoctorId(dto.getDoctorId());
            }
        }

        //循环数据 - 主要是转换时间
        for (ConsultationPageQueryVo vo : list) {
            //先判断值不为空才进入转换时间
            if (ObjectUtil.isNotEmpty(vo.getPatientSelectedDeliveryDate())
                    && ObjectUtil.isNotEmpty(vo.getDtlStartTime())
                    && ObjectUtil.isNotEmpty(vo.getDtlEndTime())
                    && ObjectUtil.isNotEmpty(vo.getTimeZone())) {
                String localDateString = Kit.getDateByTimeZone(vo.getPatientSelectedDeliveryDate(), vo.getTimeZone(), null);
                // 拼接结果字符串
                String deliveryTimePeriod = localDateString + " " + vo.getDtlStartTime() +
                        "~" + vo.getDtlEndTime() + " (GMT" +
                        (vo.getTimeZone() >= 0 ? "+" : "") + vo.getTimeZone() + ")";
                // 将拼接好的字符串设置回vo对象中
                vo.setDeliveryTimeslot(deliveryTimePeriod);
            }

        }
        return ResponseResult.success(info, totalEarning);
    }

    @Override
    public ResponseResult<PageInfo<DoctorInfoConsultationListPageVo>, BigDecimal> findPageDoctorInfoConsultationList(DoctorInfoConsultationListPageDto dto) {
        if (ObjectUtil.isEmpty(dto.getDoctorId())) {
            return ResponseResult.error("Parameter abnormality");
        }
        PageDto.startPage();
        List<DoctorInfoConsultationListPageVo> list = tblBookingMapper.findPageDoctorInfoConsultationList(dto);
        PageInfo<DoctorInfoConsultationListPageVo> info = new PageInfo<>(list);
        BigDecimal totalEarning = BigDecimal.ZERO.setScale(2, BigDecimal.ROUND_DOWN);
        if (ObjectUtil.isNotEmpty(list)) {
            //查询总额
            totalEarning = tblBookingMapper.findTotalEarningByDoctorId(dto.getDoctorId());
        }
        return ResponseResult.success(info, totalEarning);
    }

    @Override
    public ResponseResult<List<ConsultationGraphQueryVo>, BigDecimal> findConsultationGraph(ConsultationGraphQueryDto dto) {
        //先查询数据
        List<ConsultationGraphMake> list = tblBookingMapper.findConsultationGraph(dto);
        //返回的数据
        List<ConsultationGraphQueryVo> vos = new ArrayList<>();
        if (ObjectUtil.isNotEmpty(list)) {
            // 创建一个简单日期格式化器，仅包含年月日
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

            // 使用Stream API进行分组，并按日期排序
            // 将stream流通过collect收集器转换为分组后的Map
            // 其中键是格式化后的日期字符串，值是具有相同日期的ConsultationGraphMake对象列表
            Map<String, List<ConsultationGraphMake>> groupedByDate = list.stream()
                    .collect(Collectors.groupingBy(
                            // 使用日期格式化器将currentDate格式化为年月日格式的字符串
                            graphMake -> dateFormat.format(graphMake.getCurrentDate())
                    ));

            // 将map的entrySet转换为流，然后根据键（即日期）进行排序
            LinkedHashMap<String, List<ConsultationGraphMake>> sortedGroupedByDate = groupedByDate.entrySet().stream()
                    .sorted(Map.Entry.comparingByKey())
                    .collect(Collectors.toMap(
                            Map.Entry::getKey,
                            Map.Entry::getValue,
                            (oldValue, newValue) -> oldValue, // 如果有重复的key，则保持原来的value不变
                            LinkedHashMap::new // 使用LinkedHashMap来保持排序
                    ));

            // 遍历排序后的分组
            for (Map.Entry<String, List<ConsultationGraphMake>> group : sortedGroupedByDate.entrySet()) {
                String dateKey = group.getKey();
                System.out.println("key:" + dateKey);
                List<ConsultationGraphMake> graphMakes = group.getValue();
                //判断不为空才创建一个返回数据对象
                if (ObjectUtil.isNotEmpty(graphMakes)) {
                    //返回的数据
                    ConsultationGraphQueryVo vo = new ConsultationGraphQueryVo();
                    // 使用 Stream 流将所有 ConsultationGraphMake 对象的 consultAmount 和 pharmaAmount 相加
                    Optional<BigDecimal> totalAmountOptional = graphMakes.stream()
                            // 将每个 ConsultationGraphMake 对象的 consultAmount 和 pharmaAmount 相加
                            .map(consultationGraphMake -> consultationGraphMake.getConsultAmount().add(consultationGraphMake.getPharmaAmount()))
                            // 使用 reduce 方法来对所有金额进行累加
                            .reduce(BigDecimal::add);

                    // 判断 totalAmountOptional 是否存在值，如果存在，则设置小数位数和舍入模式，否则设置为 BigDecimal.ZERO
                    BigDecimal totalAmount = totalAmountOptional
                            .map(amount -> amount.setScale(2, BigDecimal.ROUND_DOWN)) // 使用 setScale 设置保留两位小数和舍入模式
                            .orElse(BigDecimal.ZERO.setScale(2, BigDecimal.ROUND_DOWN)); // 如果为空，返回 0.00
                    //设置值
                    vo.setTotalConsult(graphMakes.size());
                    vo.setTotalSales(totalAmount);
                    vo.setCurrentDate(graphMakes.get(0).getCurrentDate());
                    //装入返回的数据集合
                    vos.add(vo);
                }
            }
        }
        //这是用于计算总额的 - 某个医生所有的金额的总额
        BigDecimal totalEarning = BigDecimal.ZERO.setScale(2, BigDecimal.ROUND_DOWN);
        if (ObjectUtil.isNotEmpty(dto.getDoctorId())) {
            //医生ID不为空则查询一次总金额
            totalEarning = tblBookingMapper.findTotalEarningByDoctorId(dto.getDoctorId());
        }
        return ResponseResult.success(vos, totalEarning);
    }

    @Override
    public ResponseResult<List<ConsultationGroupMake>, Integer> findConsultationGroupList() {
        List<ConsultationGroupMake> list = tblBookingMapper.findConsultationGroupList();
        return ResponseResult.success(list);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult updateConsultationHide(BookingDTO dto) {
        //校验参数 - id和是否隐藏字段
        if (ObjectUtil.isEmpty(dto.getId()) || ObjectUtil.isEmpty(dto.getHideFromPatient())) {
            return ResponseResult.error("Parameter abnormality");
        }
        //查询这个booking是否存在并且未删除
        Example example = new Example(TblBooking.class);
        example.createCriteria()
                .andEqualTo("id", dto.getId())
                .andEqualTo("delFlag", 0);
        if (ObjectUtil.isEmpty(tblBookingMapper.selectOneByExample(example))) {
            return ResponseResult.error("Data exception, please refresh and try again!");
        }
        //准备修改对象
        TblBooking booking = new TblBooking();
        booking.setId(dto.getId());
        booking.setHideFromPatient(dto.getHideFromPatient());
        if (tblBookingMapper.updateByPrimaryKeySelective(booking) > 0) {
            return ResponseResult.success("Operation successful");
        }
        return ResponseResult.error("operation failed");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult deleteConsultation(BookingDTO dto) {
        //先校验字段值
        if (ObjectUtil.isEmpty(dto.getId())) {
            return ResponseResult.error("Parameter abnormality");
        }
        //查询这条数据 - del_flag = 0
        Example example = new Example(TblBooking.class);
        example.createCriteria()
                .andEqualTo("id", dto.getId())
                .andEqualTo("delFlag", 0);
        TblBooking booking = tblBookingMapper.selectOneByExample(example);
        if (ObjectUtil.isEmpty(booking)) {
            return ResponseResult.error("data exception");
        }
        //判断这条数据是否为已经被删除一次的数据 Deleted = 0 是未删除过,1 - 是已经删除过一次 - 再次删除则需要修改del_flag为1了
        /**
         * deleted字段已被删除
         */
//        if (booking.getDeleted() < 1) {
//            //未删除过 - 第一次删除 - 需要校验是否传入删除理由
//            if (ObjectUtil.isEmpty(dto.getDeleteReason())) {
//                return ResponseResult.error("Please enter the reason for deletion");
//            }
//            //设置为第一次删除
//            //deleted字段已被删除
////            booking.setDeleted(1);
//            //设置删除人
//            booking.setDelBy(UserUtil.getCurLoginUserId());
//            //设置删除时间
//            booking.setDelAt(new Date());
//            //设置第一次删除理由
//            booking.setDeleteReason(dto.getDeleteReason());
//            //修改进数据库
//            tblBookingMapper.updateByPrimaryKeySelective(booking);
//            return ResponseResult.success("Delete successful");
//        } else {
        booking.setDelFlag(1);
        //修改进数据库
        tblBookingMapper.updateByPrimaryKeySelective(booking);
        return ResponseResult.success("Delete successful");
//        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult updateDel(BookingDTO dto) {
        if (ObjectUtil.isEmpty(dto.getId())) {
            return ResponseResult.error("Parameter abnormality");
        }
        //准备查询条件 - 为删除过第一次 - 并且del_flag = 0
        Example example = new Example(TblBooking.class);
        example.createCriteria()
                .andEqualTo("id", dto.getId())
                .andEqualTo("deleted", 1)//为1 则代表已经删除过第一次 - 能进入这个接口也只能是删除过第一次然后进来恢复的
                .andEqualTo("delFlag", 0);
        //查询出这条booking数据
        TblBooking booking = tblBookingMapper.selectOneByExample(example);
        if (ObjectUtil.isEmpty(booking)) {
            return ResponseResult.error("illegal request");
        }
        //设置为0 - 第一次都未删除
        //deleted字段已被删除
//        booking.setDeleted(0);
        //将删除人等信息设置为null
        booking.setDelBy(null);
        booking.setDelAt(null);
        booking.setDeleteReason(null);
        //这个修改方法会将null也修改进数据库
        if (tblBookingMapper.updateByPrimaryKey(booking) > 0) {
            return ResponseResult.success("Operation successful");
        }
        return ResponseResult.error("operation failed");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult updateConsultationOrderMarkAsPacked(BookingDTO dto) {
        //校验bookingId
        if (ObjectUtil.isEmpty(dto.getId())) {
            return ResponseResult.error("illegal request");
        }
        //查询这个booking - 检查状态是否为5 - 不为5说明错误
        TblBooking booking = tblBookingMapper.selectByPrimaryKey(dto.getId());
        if (ObjectUtil.isEmpty(booking) || 1 == booking.getDelFlag()) {
            return ResponseResult.error("Data abnormality, please refresh again");
        }
        if (ObjectUtil.isEmpty(booking.getStatus()) || booking.getStatus() != 5) {
            return ResponseResult.error("Data abnormality, please refresh again");
        }
        //到这里无问题修改数据库
        booking.setStatus(6);
        return ResponseResult.update(tblBookingMapper.updateByPrimaryKeySelective(booking));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult updateConsultationOrderMarkAsCompleted(BookingDTO dto) {
        //校验bookingId
        if (ObjectUtil.isEmpty(dto.getId())) {
            return ResponseResult.error("illegal request");
        }
        //查询这个booking - 检查是否被删除
        TblBooking booking = tblBookingMapper.selectByPrimaryKey(dto.getId());
        if (ObjectUtil.isEmpty(booking) || 1 == booking.getDelFlag()) {
            return ResponseResult.error("Data abnormality, please refresh again");
        }
        booking.setStatus(99);
        return ResponseResult.update(tblBookingMapper.updateByPrimaryKeySelective(booking));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult updateConsultationOrderScheduleGrab(BookingGrabDto dto) {
        //校验
        Kit.allParamValid(dto, "bookingId", "pickUpTime", "instructionUrl");
        //查询这个booking - 检查是否被删除
        TblBooking booking = tblBookingMapper.selectByPrimaryKey(dto.getBookingId());
        if (ObjectUtil.isEmpty(booking) || 1 == booking.getDelFlag()) {
            return ResponseResult.error("Data abnormality, please refresh again");
        }
        //修改expressType为1
        //expressType字段已经删除
//        booking.setExpressType(1);
        tblBookingMapper.updateByPrimaryKeySelective(booking);
        //todo:在tbl_booking_grab添加一条数据(后续的定时任务或者是回调会把sub_status改为1)
        //生成tbl_booking_grab
        tblBookingGrabMapper.insertSelective(dto);
        return ResponseResult.success();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult updateConsultationOrderReScheduleGrab(BookingGrabDto dto) {
        //校验
        Kit.allParamValid(dto, "bookingId", "pickUpTime", "instructionUrl");
        //查询这个booking - 检查是否被删除
        //后续的定时任务或者是回调会把sub_status改为1
        TblBooking booking = tblBookingMapper.selectByPrimaryKey(dto.getBookingId());
        if (ObjectUtil.isEmpty(booking) || 1 == booking.getDelFlag()) {
            return ResponseResult.error("Data abnormality, please refresh again");
        }
        //查询tblBookingGrab
        TblBookingGrab grab = tblBookingGrabMapper.findTheLatestOneByBookingId(dto.getBookingId());
        //如果为空 - 抛出异常 - 能进入这个接口 - 并且上面sub_status状态还未被改为1 - 这个查询是肯定有一条数据的
        if (ObjectUtil.isEmpty(grab)) {
            return ResponseResult.error("Data exception, please refresh and try again");
        }
        //否则开始修改这条数据为-2 并且为已删除
        grab.setStatus(-2);
        grab.setDelFlag(1);
        tblBookingGrabMapper.updateByPrimaryKeySelective(grab);
        //生成新的数据
        TblBookingGrab insertGrab = new TblBookingGrab();
        insertGrab.setBookingId(dto.getBookingId());
        insertGrab.setPickUpTime(dto.getPickUpTime());
        insertGrab.setInstructionUrl(dto.getInstructionUrl());
        tblBookingGrabMapper.insertSelective(insertGrab);
        return ResponseResult.success("Operation successful");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult updateConsultationOrderCancelGrabDelivery(BookingGrabDto dto) {
        Kit.allParamValid(dto, "bookingId");
        //查询booking
        TblBooking booking = tblBookingMapper.selectByPrimaryKey(dto.getBookingId());
        if (ObjectUtil.isEmpty(booking) || 1 == booking.getDelFlag()) {
            return ResponseResult.error("Data abnormality, please refresh again");
        }
        booking.setSubStatus(0);
        //expressType字段已经删除
//        booking.setExpressType(0);
        //修改booking
        tblBookingMapper.updateByPrimaryKeySelective(booking);
        //查询tblBookingGrab
        TblBookingGrab grab = tblBookingGrabMapper.findTheLatestOneByBookingId(dto.getBookingId());
        if (ObjectUtil.isEmpty(grab)) {
            throw new RuntimeException("data exception");
        }
        grab.setStatus(-2);
        grab.setDelFlag(1);
        tblBookingGrabMapper.updateByPrimaryKeySelective(grab);
        return ResponseResult.success("Operation successful");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult updateConsultationOrderScheduleUparcelExpress(BookingUparcelDto dto) {
        Kit.allParamValid(dto, "bookingId", "bookingCode", "pickUpTime");
        //查询booking
        TblBooking booking = tblBookingMapper.selectByPrimaryKey(dto.getBookingId());
        if (ObjectUtil.isEmpty(booking) || 1 == booking.getDelFlag()) {
            return ResponseResult.error("Data abnormality, please refresh again");
        }
        //设置booking
        //expressType字段已经删除
//        booking.setExpressType(2);
        tblBookingMapper.updateByPrimaryKeySelective(booking);
        //问诊uparcel快递信息
        TblBookingUparcel uparcel = new TblBookingUparcel();
        uparcel.setBookingId(dto.getBookingId());
        uparcel.setBookingCode(dto.getBookingCode());
        //新生成时为1
        uparcel.setStatus(1);
        //选择特快时手动选择的时间
        uparcel.setPickUpTime(dto.getPickUpTime());
        //目前看到状态不论是新生成还是被定时任务扫中时，或者取消快递时，type这两个字段值都为6 和 1 Hour Rush
        uparcel.setUparcelDeliveryType(6);
        uparcel.setUparcelDeliveryTypeName("1 Hour Rush");
        tblBookingUparcelMapper.insertSelective(uparcel);
        return ResponseResult.success("Operation successful");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult updateConsultationOrderCancelUparcelDelivery(BookingUparcelDto dto) {
        Kit.allParamValid(dto, "bookingId");
        //查询booking
        TblBooking booking = tblBookingMapper.selectByPrimaryKey(dto.getBookingId());
        if (ObjectUtil.isEmpty(booking) || 1 == booking.getDelFlag()) {
            return ResponseResult.error("Data abnormality, please refresh again");
        }
        //expressType字段已经删除
//        booking.setExpressType(0);
        //修改booking
        tblBookingMapper.updateByPrimaryKeySelective(booking);
        //查询最新的一条
        TblBookingUparcel uparcel = tblBookingUparcelMapper.findTheLatestOneByBookingId(dto.getBookingId());
        if (ObjectUtil.isEmpty(uparcel)) {
            return ResponseResult.error("Data exception, please refresh and try again");
        }
        uparcel.setStatus(-6);
        uparcel.setOrderStatus(0);
        uparcel.setOrderSubStatus(0);
        uparcel.setDelFlag(1);
        tblBookingUparcelMapper.updateByPrimaryKeySelective(uparcel);
        return ResponseResult.success("Operation successful");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult updateConsultationOrderReScheduleUParcel(BookingUparcelDto dto) {
        Kit.allParamValid(dto, "bookingId", "bookingCode", "pickUpTime");
        //查询booking
        TblBooking booking = tblBookingMapper.selectByPrimaryKey(dto.getBookingId());
        if (ObjectUtil.isEmpty(booking) || 1 == booking.getDelFlag()) {
            return ResponseResult.error("Data abnormality, please refresh again");
        }
        //expressType字段已经删除
//        booking.setExpressType(2);
        tblBookingMapper.updateByPrimaryKeySelective(booking);
        //查询最新的一条
        TblBookingUparcel uparcel = tblBookingUparcelMapper.findTheLatestOneByBookingId(dto.getBookingId());
        if (ObjectUtil.isEmpty(uparcel)) {
            throw new RuntimeException("data error");
        }
        uparcel.setStatus(-6);
        uparcel.setOrderStatus(0);
        uparcel.setOrderSubStatus(0);
        uparcel.setDelFlag(1);
        tblBookingUparcelMapper.updateByPrimaryKeySelective(uparcel);
        //准备新数据添加
        TblBookingUparcel insertUparcel = new TblBookingUparcel();
        insertUparcel.setBookingId(dto.getBookingId());
        insertUparcel.setBookingCode(dto.getBookingCode());
        //新生成时为1
        insertUparcel.setStatus(1);
        //选择特快时手动选择的时间
        insertUparcel.setPickUpTime(dto.getPickUpTime());
        //目前看到状态不论是新生成还是被定时任务扫中时，或者取消快递时，type这两个字段值都为6 和 1 Hour Rush
        insertUparcel.setUparcelDeliveryType(6);
        insertUparcel.setUparcelDeliveryTypeName("1 Hour Rush");
        tblBookingUparcelMapper.insertSelective(insertUparcel);
        return ResponseResult.success("Operation successful");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult updateConsultationOrderScheduleUparcelStandard(BookingUparcelDto dto) {
        Kit.allParamValid(dto, "bookingId", "bookingCode");
        //查询booking
        TblBooking booking = tblBookingMapper.selectByPrimaryKey(dto.getBookingId());
        if (ObjectUtil.isEmpty(booking) || 1 == booking.getDelFlag()) {
            return ResponseResult.error("Data abnormality, please refresh again");
        }
        //expressType字段已经删除
//        booking.setExpressType(2);
        tblBookingMapper.updateByPrimaryKeySelective(booking);
        //查询最新的一条
        TblBookingUparcel uparcel = tblBookingUparcelMapper.findTheLatestOneByBookingId(dto.getBookingId());
        if (ObjectUtil.isNotEmpty(uparcel)) {
            uparcel.setStatus(-6);
            uparcel.setOrderStatus(0);
            uparcel.setOrderSubStatus(0);
            uparcel.setDelFlag(1);
            tblBookingUparcelMapper.updateByPrimaryKeySelective(uparcel);
        }
        //准备新数据添加
        TblBookingUparcel insertUparcel = new TblBookingUparcel();
        insertUparcel.setBookingId(dto.getBookingId());
        insertUparcel.setBookingCode(dto.getBookingCode());
        //新生成时为1
        insertUparcel.setStatus(1);
        //todo:这个时间是自动计算的，目前不知道怎么计算
        insertUparcel.setPickUpTime(null);
        insertUparcel.setUparcelDeliveryType(1);
        insertUparcel.setUparcelDeliveryTypeName("3 hours express");
        tblBookingUparcelMapper.insertSelective(insertUparcel);
        return ResponseResult.success("Operation successful");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult updateConsultationOrderMarkAsDelivering(BookingDTO dto) {
        if (ObjectUtil.isEmpty(dto.getId())) {
            return ResponseResult.error("Parameter abnormality");
        }
        //查询这个booking
        TblBooking booking = tblBookingMapper.selectByPrimaryKey(dto.getId());
        if (ObjectUtil.isEmpty(booking) || 1 == booking.getDelFlag()) {
            return ResponseResult.error("Data abnormality, please refresh again");
        }
        //修改booking的状态为9
        booking.setStatus(9);
        tblBookingMapper.updateByPrimaryKeySelective(booking);
        return ResponseResult.success("Operation successful");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult updateConsultationListMarkAsPaid(BookingDTO dto) {
        if (ObjectUtil.isEmpty(dto.getId())) {
            return ResponseResult.error("Parameter abnormality");
        }
        //查询这个booking
        TblBooking booking = tblBookingMapper.selectByPrimaryKey(dto.getId());
        if (ObjectUtil.isEmpty(booking) || 1 == booking.getDelFlag()) {
            return ResponseResult.error("Data abnormality, please refresh again");
        }
        //判断如果不为4 - 返回错误信息
        if (4 != booking.getStatus()) {
            return ResponseResult.error("Data error, please try again later");
        }
        //修改状态为5 并且将sub_status 修改为0
        booking.setStatus(5);
        booking.setSubStatus(0);
        tblBookingMapper.updateByPrimaryKeySelective(booking);
        return ResponseResult.success("Operation successful");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult updateConsultationListUpdateProfile(BookingDTO dto) {
        return null;
    }

    @Override
    public ResponseResult downloadMedicationCertificationPdf(HttpServletResponse response, String bookingId) {
        if (ObjectUtil.isEmpty(bookingId)) {
            return ResponseResult.error("illegal request");
        }
        try {
            //查询数据
            MedicationCertificationPdfVo data = tblBookingMapper.getMedicationCertificationPdfData(bookingId);
            //判断不为空才进入
            if (ObjectUtil.isNotEmpty(data)) {
                // dd表示日，MMM表示月份的缩写形式，yy表示两位数的年份
                // 使用Locale.ENGLISH来确保月份的缩写是英文的
                SimpleDateFormat formatter = new SimpleDateFormat("dd MMM yy", Locale.ENGLISH);
                //判断是否有病假条:0-否,1-是
                if (1 == data.getNeedMedicalCertification()) {
                    //判断全都不为空才行
                    if (ObjectUtil.isNotEmpty(data.getMedicalCertificationDays())
                            && ObjectUtil.isNotEmpty(data.getMedicalCertificationBeginDate())) {
                        //开始转换时间格式
                        // 使用format()方法将日期转换
                        String strDate = formatter.format(data.getMedicalCertificationBeginDate());
                        //开始拼接病假条
                        data.setSickLetterNote("The above mentioned individual has been certified Unfit <br>" +
                                "for Duty for " + data.getMedicalCertificationDays() + " day " + "with effect from " + strDate);
                    }

                }
                //设置当前时间并且转换
                data.setCurrentDate(formatter.format(new Date()));
                //设置VisitDate
                data.setVisitDate(formatter.format(data.getCreatedOn()));
                //国际化
                String lastLanguage = data.getLastLanguage();
                data.setMcrNoText(TranslationUtil.getContentLastLanguage("MCR_NO",lastLanguage));
                data.setIdNoText(TranslationUtil.getContentLastLanguage("ID_NO",lastLanguage));
                data.setNameText(TranslationUtil.getContentLastLanguage("NAME",lastLanguage));
                data.setVisitDateText(TranslationUtil.getContentLastLanguage("VISITDATE",lastLanguage));
                data.setCertificateNoText(TranslationUtil.getContentLastLanguage("CERTIFICATE_NO",lastLanguage));
                data.setNoteText(TranslationUtil.getContentLastLanguage("NOTE",lastLanguage));

                HashMap<String, Object> mapData = Maps.newHashMap();
                mapData.put("data", data);
                String templateContent = HtmlUtils.getTemplateContent("MedicalCertificate.ftl", mapData);
                //名称动态data.getCertificateNo()：MC+booking的code
                HtmlUtils.html2Pdf(response, templateContent, data.getCertificateNo() != null ? data.getCertificateNo() : "Medication Certification");
            } else {
                return ResponseResult.error();
            }
        } catch (Exception e) {
            log.error("error occurs when downloading file,{}", e);

        }
        return ResponseResult.success("ok");
    }

    @Override
    public ResponseResult<List<BookingGrabListVo>, Object> findGrabListByBookingId(BookingGrabDto dto) {
        if (ObjectUtil.isEmpty(dto.getBookingId())) {
            return ResponseResult.error("illegal request");
        }
        //查询列表
        List<BookingGrabListVo> vos = tblBookingGrabMapper.findGrabListByBookingId(dto.getBookingId());
        //循环去做时间格式转换
        if (ObjectUtil.isNotEmpty(vos)) {
            for (BookingGrabListVo vo : vos) {
                //判断时间对象以及时区不为空才进入转换时间 - 这里转换之后的时间字符串格式为：Jan 05 2024 16:18:00 (GMT+8)
                if (ObjectUtil.isNotEmpty(vo.getTimezone())) {
                    if (ObjectUtil.isNotEmpty(vo.getPickUpTime())) {
                        vo.setPickUpTimeStr(Kit.formatUtcDate(vo.getPickUpTime(), vo.getTimezone()));
                    }
                    if (ObjectUtil.isNotEmpty(vo.getRequestTiming())) {
                        vo.setRequestTimingStr(Kit.formatUtcDate(vo.getRequestTiming(), vo.getTimezone()));
                    }
                }
            }
        }
        return ResponseResult.success(vos);
    }

    @Override
    public ResponseResult<List<BookingUparcelListVo>, Object> findUparcelListByBookingId(BookingUparcelDto dto) {
        if (ObjectUtil.isEmpty(dto.getBookingId())) {
            return ResponseResult.error("illegal request");
        }
        List<BookingUparcelListVo> vos = tblBookingUparcelMapper.findUparcelListByBookingId(dto.getBookingId());
        //循环做时间转换
        for (BookingUparcelListVo vo : vos) {
            //判断时区值以及时间对象不为空才转换
            if (ObjectUtil.isNotEmpty(vo.getTimezone())) {
                if (ObjectUtil.isNotEmpty(vo.getPickUpTime())) {
                    //调用方法转换直接设置值
                    vo.setPickUpTimeStr(Kit.formatUtcDate(vo.getPickUpTime(), vo.getTimezone()));
                }
                if (ObjectUtil.isNotEmpty(vo.getRequestTiming())) {
                    vo.setRequestTimingStr(Kit.formatUtcDate(vo.getRequestTiming(), vo.getTimezone()));
                }
            }
        }
        return ResponseResult.success(vos);
    }
}
